import { SETUSERINFO, SETAUTH, HANDLELOGOUT } from '@/store/actionTypes/user.js'
import StorageUtils from '@/utils/storageUtils';
const initalState = {
  user_id: '',
  username: "", //用户名
  userInfo: {}, //用户详细信息
  auth: '',// 登录成功后用户token
}

/***
 * 
 * 管理用户的状态
 */
const userReduce = (state = initalState, action) => {
  switch (action.type) {
    case SETUSERINFO:
      return { ...state, userInfo: action.payload }
    case SETAUTH:
      const data = action.payload
      const { user_id, username } = data
      saveAuth(data)
      saveToken(data.access_token)
      return { user_id, username, auth: `Bearer ${data.access_token}`, userInfo: { user_id, username } }
    case HANDLELOGOUT:
      //       是否選擇記住我
      clearStorage();
      return { user_id: '', username: "", userInfo: {}, auth: '' };
    default:
      return state
  }
}

const saveAuth = async (auth) => {
  const jsonValue = JSON.stringify(auth)
  await StorageUtils.setItem("auth", jsonValue);
};
const saveToken = async (token) => {
  const jsonValue = JSON.stringify({ token: `Bearer ${token}` })
  await StorageUtils.setItem("token", jsonValue);
};
const clearStorage = async () => {
  await StorageUtils.removeItem('auth');
  await StorageUtils.removeItem('token');
};
export default userReduce